package com.binvshe.binvshe.mine.utils;

import android.content.Context;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.mine.model.CityEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * 全国省份城市操作类
 */
public class AreaDataUtil {

    /**
     * 所有的省市String
     */
    public String AREAS_DATA;

    private static final String FILE_NAME = "city.txt";

    private HashMap<String, List<String>> mCityMap = new HashMap<>();
    private final CityEntity mCityEntity;

    public AreaDataUtil(Context context) {
        AREAS_DATA = getJsonFile(context);
        mCityEntity = GsonUtils.parseJSON(AREAS_DATA, CityEntity.class);
        getAllCityMap();
    }

    private String getJsonFile(Context context) {

        String cityJson = "";
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        try {
            is = context.getResources().getAssets().open(FILE_NAME);
            inputStreamReader = new InputStreamReader(is);
            BufferedReader bf = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = bf.readLine()) != null)
                cityJson += line;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cityJson;
    }

    /**
     * 获得全国省份的列表
     *
     * @return
     */
    public ArrayList<String> getProvinces() {
        ArrayList<String> provinceList = new ArrayList<>();
        List<CityEntity.DictBean> dict = mCityEntity.getDict();
        for (int i = 0; i < dict.size(); i++) {
            String province = dict.get(i).getString();
            provinceList.add(province);
        }
        return provinceList;
    }

    /**
     * 根据省份获取城市列表
     *
     * @return
     */
    private void getAllCityMap() {
        List<CityEntity.DictBean> dict = mCityEntity.getDict();
        for (int i = 0; i < dict.size(); i++) {
            String province = dict.get(i).getString();
            List<String> cityList = mCityEntity.getDict().get(i).getArray().getString();
            mCityMap.put(province, cityList);
        }
    }

    /**
     * 根据省份查找对应的城市列表
     *
     * @return 城市集合
     */
    public ArrayList<String> getCityByProvince(String provinceStr) {

        List<String> list = mCityMap.get(provinceStr);
        ArrayList<String> arrList = new ArrayList<>();
        for (String city : list) {
            arrList.add(city);
        }
        return arrList;
    }
}
